package com.tsj.spzx.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.tsj.spzx.model.entity.user.UserInfo;
import com.tsj.spzx.utils.AuthContextThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器，拦截所有以api开头的请求，将用户信息存入ThreadLocal中       拦截器还要注册
 *
 * 登陆验证，已在网关中的过滤器中实现
 */
@Component
public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        String token = request.getHeader("token");
        String JsonUserInfo =redisTemplate.opsForValue().get(token);
        // 无需再次验证, 存入ThreadLocal中
        UserInfo userInfo = JSONObject.parseObject(JsonUserInfo, UserInfo.class);
        AuthContextThreadLocalUtil.setUserInfo(userInfo);
        return true;
    }
}
